package com.mezz.bones.im.gateway.boot;

import com.mezz.bones.im.gateway.handler.AppIdParamHandler;
import com.mezz.bones.im.gateway.handler.codec.Encode2WebsocketHandler;
import com.mezz.bones.im.gateway.handler.codec.Decode2ImMessageHandler;
import com.mezz.bones.im.gateway.handler.HandshakeHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class WebsocketServerBoot extends ImServerBoot {

    @Resource
    private AppIdParamHandler appIdParamHandler;

    @Resource
    private Encode2WebsocketHandler encode2WebsocketHandler;

    @Resource
    private Decode2ImMessageHandler decode2ImMessageHandler;

    @Resource
    private HandshakeHandler handshakeHandler;

    @Override
    protected void encodeMessage(ChannelPipeline pipeline) {
        //编码 返回数据给客户端
        pipeline.addLast(encode2WebsocketHandler);
    }

    @Override
    protected void decodeMessage(ChannelPipeline pipeline) {
        // HTTP请求的解码和编码
        pipeline.addLast(new HttpServerCodec());

        // 把多个消息转换为一个单一的FullHttpRequest或是FullHttpResponse
        pipeline.addLast(new HttpObjectAggregator(65536));

        // 处理大数据流
        pipeline.addLast(new ChunkedWriteHandler());

        // 添加appId参数处理Handler
        pipeline.addLast(appIdParamHandler);

        // webSocket 数据压缩扩展
        pipeline.addLast(new WebSocketServerCompressionHandler());
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, true));

        // 握手完成处理
        pipeline.addLast(handshakeHandler);

        //解析成自定义业务模型
        pipeline.addLast(decode2ImMessageHandler);

    }
}
